package com.lc.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author liuc
 * @date 2021/6/28
 * @description
 **/
@Slf4j
@Component
public class TokenFilter implements GlobalFilter {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<HttpCookie> token = exchange.getRequest().getCookies().get("token");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        String path = request.getURI().getPath();
        //token合法直接重定向至
        if(path.startsWith("/user") || path.startsWith("/code") || token != null){
            return chain.filter(exchange);
        }else{
            response.setStatusCode(HttpStatus.FORBIDDEN);
            log.debug("=====>IP:" + clientIp + " token为null");
            String data = "访问该资源需先登录!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

}
